import seeting from "@/config/seeting";
import { useUserStore } from "@/stores/modules/user";
import { refeshToken as handlerRefeshToken } from "@/api/user/user"
export const useRefeshToken = () => {
    interface RefeshToken {
        refeshToken: string,
        datetime: number
    }
    const user = useUserStore()
    // 获取刷新token所需要的数据
    const refeshToken = ref<RefeshToken>({
        refeshToken: "",
        datetime: 0
    })
    let timer: number | null = null
    function refreshToken() {
        timer = setInterval(() => {
            let refesh_token = localStorage.getItem("refeshToken")
            if (refesh_token) {
                refeshToken.value = JSON.parse(refesh_token)
            }
            if (refeshToken.value.datetime <= 0) return
            // token过期的剩余时间
            let calcTime = new Date().getTime() - refeshToken.value.datetime

            // 检测token过期时间 如果超过3000秒后刷新token
            if (calcTime > seeting.tokenTime * 1000) {
                // console.log("刷新一次token");
                let par = {
                    tenantId: "000000", //租户ID
                    refresh_token: refeshToken.value.refeshToken,
                    grant_type: "refresh_token",
                    scope: "all",
                }
                handlerRefeshToken(par).then((res: any) => {
                    user.setUserInfo(res)
                    user.setToken(res.access_token)
                    user.setRefeshToken(res.refresh_token)
                })
            } else {
                // console.log("token还未过期");
            }

        }, 10000)
    }
    return { refreshToken }
}